//
//  CPHISTORYController.m
//  ChinaPoem
//
//  Created by 赵俊明 on 2019/3/4.
//  Copyright © 2019 赵俊明. All rights reserved.
//

#import "CPHISTORYController.h"
#import "CPHeadFooter.h"
#import "CPContentController.h"

@interface CPHISTORYController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, weak) UITableView *hisTab;
@property (nonatomic, strong) NSMutableArray *dataSource;
@end

@implementation CPHISTORYController

- (void)viewDidLoad
{
    [super viewDidLoad];
    UITableView *hisTab = [[UITableView alloc] initWithFrame:self.view.bounds style:(UITableViewStyleGrouped)];
    [hisTab registerClass:[CPHistoryCell class] forCellReuseIdentifier:@"history"];
    hisTab.delegate = self;
    hisTab.dataSource = self;
    hisTab.sectionHeaderHeight = 0;
    hisTab.sectionFooterHeight = 0;
    hisTab.backgroundColor = [UIColor clearColor];
    hisTab.separatorColor = hisTab.backgroundColor;
    [self.view addSubview:hisTab];
    if ([hisTab respondsToSelector:@selector(setSectionIndexColor:)]) {
        hisTab.sectionIndexBackgroundColor = [UIColor clearColor];
        hisTab.sectionIndexColor = [UIColor grayColor];
    }
    [hisTab mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
            make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.top.mas_equalTo(self.view.mas_top);
            make.bottom.mas_equalTo(self.view.mas_bottom);
        }
        make.width.mas_equalTo(self.view);
    }];
    self.hisTab = hisTab;
    [self pullRefresh];
}

- (void)pullRefresh
{
    JMSelf(weakSelf);
    self.hisTab.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.dataSource = [weakSelf descSortArray];
        sleep(.5);
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.hisTab reloadData];
            [weakSelf.hisTab.mj_header endRefreshing];
        });
    }];
    
    [self.hisTab.mj_header beginRefreshing];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    CPHistoryModel *model = _dataSource[section];
    return [model.models count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CPHistoryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"history" forIndexPath:indexPath];
    CPHistoryModel *model = _dataSource[indexPath.section];
    cell.model = model.models[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CPContentController *content = [[CPContentController alloc] init];
    CPHistoryModel *model =_dataSource[indexPath.section];
    CPModel *mo = model.models[indexPath.row];
    NSMutableArray *array = [[CPSQLTools cp_sharedInstance] cp_query_poem:[NSString stringWithFormat:@"select * from poems where pk = %ld", [mo.cp_ids integerValue]]];
    content.model = array.firstObject;
    content.title = content.model.cp_title;
    [self.navigationController pushViewController:content animated:YES];
}

#pragma mark -- headerView
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    CPHeadFooter *header = [CPHeadFooter cp_headTableView:tableView];
    CPHistoryModel *model = self.dataSource[section];
    NSString *date = [model.date stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSString *year = [date substringWithRange:NSMakeRange(0, 4)];
    NSString *month = [date substringWithRange:NSMakeRange(4, 2)];
    NSString *day = [date substringWithRange:NSMakeRange(6, 2)];
    header.groups = [NSString stringWithFormat:@"%@年%@月%@日", year, month, day];
    return header;
}

// section头部间距
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 64;
}

// 1> 对取出的数组进行分组, 将数首字母相同的名字放到一个数组中
- (NSMutableArray *)descSortArray
{
    NSMutableArray *array = [[CPSQLTools cp_sharedInstance] cp_historyORSave:@"history"];
    NSMutableArray *targetArray = [@[] mutableCopy];
    for (int i = 0; i < array.count; i ++) {
        CPModel *model = array[i];
        NSInteger m = [self cp_day:model.cp_timeTsp];
        NSMutableArray *tempArray = [@[] mutableCopy];
        [tempArray addObject:model];
        for (int j = i+1; j < array.count; j ++) {
            CPModel *model = array[j];
            NSInteger n = [self cp_day:model.cp_timeTsp];
            if(m == n){
                [tempArray addObject:model];
                [array removeObjectAtIndex:j];
                j -= 1;
            }
        }
        [targetArray addObject:tempArray];
    }
    
    // 对获得数组进行一次冒泡排序
    NSInteger number = targetArray.count;
    for (int i = 0; i < number-1; i ++) {
        for (int j = 0; j < number-i-1; j++) {
            NSMutableArray *subArr = targetArray[j];
            if (subArr.count > j+1) {
                CPModel *model;
                if (j < subArr.count) {model = subArr[j];}
                NSInteger m = [self cp_day:model.cp_timeTsp];
                NSMutableArray *subArr1 = targetArray[j+1];
                CPModel *model0;
                if (j < subArr1.count) {model0 = subArr1[j];}
                NSInteger n = [self cp_day:model0.cp_timeTsp];
                if (m>n) {
                    NSMutableArray *temp = subArr;
                    [targetArray replaceObjectAtIndex:j withObject:subArr1];
                    [targetArray replaceObjectAtIndex:j+1 withObject:temp];
                }
            }
        }
    }
    
    NSMutableArray *items = [NSMutableArray array];
    for (NSMutableArray *item in targetArray) {
        CPHistoryModel *model = [CPHistoryModel new];
        model.models = item;
        CPModel *mo = item.firstObject;
        model.date = mo.cp_timeTsp;
        [items addObject:model];
    }
    return items;
}

- (NSInteger)cp_day:(NSString *)tStr
{
    NSArray *comps = [tStr componentsSeparatedByString:@"-"];
    if (comps.count > 3) {
        return[comps[2] integerValue];
    }else{
        return 100;
    }
}

@end

#pragma mark - **************** CPHistoryCell
@implementation CPHistoryCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.backgroundColor = [UIColor clearColor];
        UILabel *tTit = [[UILabel alloc] initWithFrame:CGRectZero];
        tTit.textAlignment = NSTextAlignmentLeft;
        tTit.font = kFont(16.0);
        [self.contentView addSubview:tTit];
        self.tTit = tTit;
        self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        self.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    return self;
}

- (void)setModel:(CPModel *)model
{
    _model = model;
    _tTit.text = [NSString stringWithFormat:@"%@--%@", model.cp_title, model.cp_author];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    _tTit.frame = CGRectMake(10, 8, self.width*0.8, self.height-10);
}
@end

